﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using DataAccess;
using System.Globalization;

//using InterveningPolice = Model.InterveningPolice;
using Model.EntityModel;
using CustomControls;
using System.Collections.ObjectModel;

namespace Project
{
    /// <summary>
    /// Interaction logic for DirectActionRegisterContent.xaml
    /// </summary>
    
    
    public partial class DirectActionRegisterContent : UserControl
    {
        SearchFunctionary search;
        InterveningPolice official = new InterveningPolice();
        Person aggressor = new Person();
        Actor aggressorActor = new Actor();
        Person complainant = new Person();
        Actor complainantActor = new Actor();
        Complaint complaint = new Complaint();
        DirectAction directAction = new DirectAction();
        Employee functionary = new Employee();
        String Hours;
        String Minutes;        

        public DirectActionRegisterContent()
        {

            InitializeComponent();
            UIWindowManager.SetWindowTitle(this, "Brigada De Protección a la Familia - Registrar Accion Directa");
            lblCaseDate.Content = DateTime.Now.Date;
            datePickerBirthDateCamplainant.DisplayDateStart = DateTime.Now.AddYears(-100);
            datePickerBirthDateCamplainant.DisplayDateEnd = DateTime.Now;
            datePickerFactDate.DisplayDateStart = DateTime.Now.AddDays(-10);
            datePickerFactDate.DisplayDateEnd = DateTime.Now;
            datePickerBirthDateAggressor.DisplayDateStart = DateTime.Now.AddYears(-100);
            datePickerBirthDateAggressor.DisplayDateEnd = DateTime.Now;
            SetRules();
        }

        private void setRulesOffice()
        {
            //policia interviniente
            TxtBoxOfficeName.AddValitationRule(new ShortStringRule(3));
            TxtBoxOfficePN.AddValitationRule(new ShortStringRule(3));

            TxtBoxOfficeMN.DeactivateBlankValidation();
            TxtBoxOfficeDepartament.AddValitationRule(new ShortStringRule(3));
            TxtBoxPoliceCI.AddValitationRule(new ShortStringRule(4));

            TxtBoxOfficeZone.AddValitationRule(new ShortStringRule(3));
            TxtBoxOfficeWorkPlace.AddValitationRule(new ShortStringRule(2));
        }

        private void setRulesFact()
        {
            TxtBoxFactNature.AddValitationRule(new ShortStringRule(3));
            TxtBoxReport.AddValitationRule(new ShortStringRule(10));
        }

        private void setRulesDenounced()
        {
            //denunciado
            TxtBoxDenouncedName.AddValitationRule(new ShortStringRule(3));
            TxtBoxDenouncedPN.AddValitationRule(new ShortStringRule(3));
            TxtBoxDenouncedMN.DeactivateBlankValidation();
            TxtBoxDenouncedCI.AddValitationRule(new ShortStringRule(5));
            TxtBoxDenouncedOccupation.AddValitationRule(new ShortStringRule(3));
            TxtBoxDenouncedAddress.AddValitationRule(new ShortStringRule(3));
            TxtBoxDenouncedPhone.DeactivateBlankValidation();
            TxtBoxDenouncedPhone.DeactivateBlankValidation();
            TxtBoxDenouncedBornPlace.AddValitationRule(new ShortStringRule(3));
            TxtBoxDenouncedZone.AddValitationRule(new ShortStringRule(3)); 
        }

        private void setRulesComplainant()
        {
            //denunciante
            TxtBoxComplainantName.AddValitationRule(new ShortStringRule(3));
            TxtBoxComplainantPN.AddValitationRule(new ShortStringRule(3));
            TxtBoxComplainantMN.DeactivateBlankValidation();
            TxtBoxComplainantCI.AddValitationRule(new ShortStringRule(5));
            TxtBoxComplainantOccupation.AddValitationRule(new ShortStringRule(3));
            TxtBoxComplainantAddress.AddValitationRule(new ShortStringRule(3));
            TxtBoxComplainantPhone.DeactivateBlankValidation();
            TxtBoxComplainantZone.AddValitationRule(new ShortStringRule(3));
            TxtBoxComplainantBornPlace.AddValitationRule(new ShortStringRule(3));
        }

        private void setRulesPolice()
        {
            //policia encargada
            TxtBoxPoliceName.AddValitationRule(new ShortStringRule(3));
            TxtBoxPolicePName.AddValitationRule(new ShortStringRule(3));
            TxtBoxPoliceMName.DeactivateBlankValidation();
            TxtBoxPoliceCI.AddValitationRule(new ShortStringRule(4));
        }

        private void SetRules()
        {
            setRulesOffice();
            setRulesFact();
            setRulesDenounced();
            setRulesComplainant();
            setRulesPolice();          
        }

        private bool GetOfficial()
        {
            try
            {
                official.CI = Convert.ToInt64(TxtBoxOfficeCI.Text.Trim());
                official.Name = TxtBoxOfficeName.Text.Trim();
                official.PaternalName = TxtBoxOfficePN.Text.Trim();
                official.MaternalName = TxtBoxOfficeMN.Text.Trim();
                official.PoliceStation = TxtBoxOfficeDepartament.Text.Trim();
                official.Place = TxtBoxOfficeWorkPlace.Text.Trim();
                official.Zone = TxtBoxOfficeZone.Text.Trim();
                
                return true;
            }
            catch
            {
                MessageBox.Show("error al obtener los datos del hecho");
                return false;
            }
        }

        private bool GetFact(long CIInterveningPolice, long IdComplainant, long CIEmployee, long IdAggressor)
        {
            try
            {
                directAction.CIEmployee = CIEmployee;
                directAction.CIInterveningPolice = CIInterveningPolice;
                directAction.IncidentReport = TxtBoxReport.Text.Trim();
                TimeSpan time = new TimeSpan(Convert.ToInt32(Hours), Convert.ToInt32(Minutes), 0);
                directAction.IncidentTime = time;
                directAction.RegistrationDate = DateTime.Now;
                directAction.IncidentNature = TxtBoxFactNature.Text.Trim();
                directAction.CompleteComplaint = false;
                directAction.Status = true;
                return true;
            }
            catch(Exception ex)
            {
                MessageBox.Show("error al obtener los datos del hecho");
                return false;
            }
        }

        private bool GetComplainant()
        {
            try
            {
                complainant.Id = TxtBoxComplainantCI.Text + DateTime.Now.Date.ToString(CultureInfo.GetCultureInfo("es-ES").DateTimeFormat.ShortDatePattern);
                complainant.CiPassport = Convert.ToInt64(TxtBoxComplainantCI.Text.Trim());
                complainant.Name = TxtBoxComplainantName.Text.Trim();
                complainant.PaternalName = TxtBoxComplainantPN.Text.Trim();
                complainant.MaternalName = TxtBoxComplainantMN.Text.Trim();
                complainant.BirthDate = datePickerBirthDateCamplainant.DisplayDate;
                complainant.Phone = TxtBoxComplainantPhone.Text;
                complainant.Ocupation = TxtBoxComplainantOccupation.Text.Trim();
                complainant.BornCity = TxtBoxComplainantBornPlace.Text.Trim();
                complainant.Address = TxtBoxComplainantAddress.Text.Trim();
                complainant.Zone = TxtBoxComplainantZone.Text.Trim();
                complainant.RegisterDate = DateTime.Now.Date;
                complainant.Status = true;
                return true;
            }
            catch
            {
                MessageBox.Show("error al obtener los datos del hecho");
                return false;
            }
        }

        private bool GetAggressor()
        {
            try
            {
                aggressor.Id = TxtBoxDenouncedCI.Text + DateTime.Now.Date.ToString(CultureInfo.GetCultureInfo("es-ES").DateTimeFormat.ShortDatePattern);
                aggressor.Name = TxtBoxDenouncedName.Text.Trim();
                aggressor.PaternalName = TxtBoxDenouncedPN.Text.Trim();
                aggressor.MaternalName = TxtBoxDenouncedMN.Text.Trim();
                aggressor.CiPassport = Convert.ToInt64(TxtBoxDenouncedCI.Text.Trim());
                aggressor.BirthDate = datePickerBirthDateAggressor.DisplayDate;
                aggressor.Phone = TxtBoxDenouncedPhone.Text;
                aggressor.Ocupation = TxtBoxDenouncedOccupation.Text.Trim();
                aggressor.BornCity = TxtBoxDenouncedBornPlace.Text.Trim();
                aggressor.Address = TxtBoxDenouncedAddress.Text.Trim();
                aggressor.Zone = TxtBoxDenouncedZone.Text.Trim();
                aggressor.RegisterDate = DateTime.Now.Date;
                return true;
            }
            catch
            {
                MessageBox.Show("error al obtener los datos del hecho");
                return false;
            }
        }

        private bool registerComplaint()
        {
            try
            {
                complaint.IncidentDate = datePickerFactDate.SelectedDate;
                complaint.IncidentPlace = rbtnPrivateAmbit.IsChecked == true ? "Ambito Privado" : rbtnPublicAmbit.IsChecked == true ? "Ambito Publico" : null;
                complaint.IncidentZone = rbtnZoneCentral.IsChecked == true ? "Urbano Central" : (rbtnZoneRural.IsChecked == true ? "Rural" : rbtnZonePeriferic.IsChecked == true ? "Urbano Periferica" : null);
                complaint.IdDirectAction = directAction.Id;
                complaint=DataAccess.ComplaintDataAccess.RegisterComplaint(complaint);
                lblCaseNumber.Content = complaint.IncidentDate;
                return true;
            }
            catch 
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("error al registrar");
                return false;
            }
        }

        private bool CheckHasErrors()
        {
            bool res = false;
            foreach (var control in Content.Children)
            {
                GroupBox gp = control as GroupBox;
                if (gp != null)
                {
                    foreach (var ctrl in (gp.Content as Grid).Children)
                    {
                        TextBox tb = ctrl as TextBox;
                        if (tb != null)
                        {
                            tb.GetBindingExpression(TextBox.TextProperty).UpdateSource();
                            if (Validation.GetHasError(tb))
                                res = true;
                        }
                        ValidationComboBox cb = ctrl as ValidationComboBox;
                        if (cb != null)
                        {
                            cb.LostFocusEventHandler(cb, null);
                            if (Validation.GetHasError(cb))
                                res = true;
                        }
                        ValidDatePicker dtp = ctrl as ValidDatePicker;
                        if (dtp != null)
                        {
                            dtp.GetBindingExpression(DatePicker.TextProperty).UpdateSource();
                            dtp.LostFocusEventHandler(dtp, null);
                            if (Validation.GetHasError(dtp))
                                res = true;
                        }
                    }
                }
            }
            if (!(rbtnPrivateAmbit.IsChecked == true || rbtnPublicAmbit.IsChecked == true))
            {
                LblError.Content = "!!!!";
                res = true;
            }
            if (!(rbtnZoneCentral.IsChecked == true || rbtnZonePeriferic.IsChecked == true || rbtnZoneRural.IsChecked == true))
            {
                LblError1.Content = "!!!!";
                res = true;
            }
            return res;
        }

        private void CreateActor(int type, String idPerson, long idComplaint)
        {
           
            if (type == 1)
            {
                aggressorActor.IdComplaint = idComplaint;
                aggressorActor.IdPerson = idPerson;
                aggressorActor.Type = "Agresor";
            }
            if (type == 2)
            {
                complainantActor.IdComplaint = idComplaint;
                complainantActor.IdPerson = idPerson;
                complainantActor.Type = "Denunciante";
            }
        }

        private void ManageComplainant()
        {
            Person complainant2 = PersonAndActorDataAccess.GetPersonByCi(complainant.CiPassport);
            if (complainant2 == null)
            {
                complainant = PersonAndActorDataAccess.InsertPerson(complainant);
                if (complainant == null)
                {
                    MessageBox.Show("Error al insertar denunciante");
                }
                complainantActor.IdPerson = complainant.Id;
            }
            else
                complainantActor.IdPerson = complainant2.Id;
            complainantActor.IdComplaint = complaint.Id;
            complainantActor.Type = "Denunciante";
            DataAccess.PersonAndActorDataAccess.InsertActor(complainantActor);
        }

        private void ManageAggressor()
        {
            Person aggressor2 = PersonAndActorDataAccess.GetPersonByCi(aggressor.CiPassport);
            if (aggressor2 == null)
            {
                aggressor = PersonAndActorDataAccess.InsertPerson(aggressor);
                if (aggressor == null)
                {
                    MessageBox.Show("Error al insertar agresor");
                }
                aggressorActor.IdPerson = aggressor.Id;
            }
            else
                aggressorActor.IdPerson = aggressor2.Id;
            aggressorActor.IdComplaint = complaint.Id;
            aggressorActor.Type = "Agresor";
            DataAccess.PersonAndActorDataAccess.InsertActor(aggressorActor);
        }

        private void ManageOffice()
        {
            bool police2 = InterveningPoliceDataAccess.PoliceAlreadyExists(official.CI);
            if (police2 == false)
            {
                official = InterveningPoliceDataAccess.InsertInterveningPolice(official);
                if (official == null)
                {
                    MessageBox.Show("Error al insertar oficial");
                }
            }
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                bool hasErrors = CheckHasErrors();
                if (!hasErrors)
                {
                    if (GetOfficial() && GetComplainant() && GetAggressor())//si todo esta bien
                    {
                        if (GetFact(official.CI, complainant.CiPassport, functionary.CI, aggressor.CiPassport))
                        {
                            ManageOffice();                            
                            directAction = DirectActionDataAccess.InsertDirectAction(directAction);
                            bool rc = registerComplaint();
                            ManageAggressor();
                            ManageComplainant();
                            if (rc)
                            {
                                MessageBoxResult result = Xceed.Wpf.Toolkit.MessageBox.Show("Reporte de Accion Directa Registrado! Desea Imprimir el documento?", "Information", MessageBoxButton.YesNo, MessageBoxImage.Question);
                                if (result == MessageBoxResult.Yes)
                                {
                                    var items = new ObservableCollection<UserControl>();
                                    items.Add(new PrintDirectAction(complaint.Id));
                                    items.Add(new PrintDirectionActionPart2(complaint.Id));
                                    var a = new PrintPreviewDialogV2(items);
                                    a.ShowDialog();
                                }
                                else
                                {
                                    Xceed.Wpf.Toolkit.MessageBox.Show("Puede imprimir la accion directa posteriormente, entrando a Ver Denuncias, click sobre la denuncia selecciona la opción Ver Accion Directa",
                                                               "Información!", MessageBoxButton.OK, MessageBoxImage.Information);
                                }
                                UIWindowManager.CleanWindow(this);
                            }
                            else
                            {
                                Xceed.Wpf.Toolkit.MessageBox.Show("Error en el servidor Intente registrar los datos mas tarde", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                UIWindowManager.CleanWindow(this);
                            }
                        }

                    }
                }
                else
                {
                    Xceed.Wpf.Toolkit.MessageBox.Show("Todos los campos deben ser llenados", "Aviso", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Errores al insertar Accion directa", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        

        private void comboBoxComplainantMaritalStatus_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBoxComplainantMaritalStatus.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)comboBoxComplainantMaritalStatus.SelectedValue;
                complainant.CivilStatus = item.Content.ToString();
            }
        }

        private void comboBoxDenouncedMaritalState_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBoxDenouncedMaritalState.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)comboBoxDenouncedMaritalState.SelectedValue;
                aggressor.CivilStatus = item.Content.ToString();
            }
        }

        private void cmbBoxHours_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbBoxHours.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)cmbBoxHours.SelectedValue;
                Hours = item.Content.ToString();
            }
        }

        private void cmbBoxMinutes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbBoxMinutes.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)cmbBoxMinutes.SelectedValue;
                Minutes = item.Content.ToString();
            }
        }

        private void comboBoxOfficeRank_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBoxOfficeRank.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)comboBoxOfficeRank.SelectedValue;
                official.Rank = item.Content.ToString();
            }
        }
           
        void getEmployeeEventHandler(object sender, RoutedEventArgs e)
        {
            try
            {
                functionary.CI = search.Employee.CI;
                functionary = EmployeeDataAccess.GetEmployeeByCi(functionary.CI);
                search.Close();
                TxtBoxPoliceCI.Text = functionary.CI.ToString();
                TxtBoxPoliceName.Text = functionary.Name;
                TxtBoxPolicePName.Text = functionary.PaternalName;
                TxtBoxPoliceMName.Text = functionary.MaternalName;
                TxtBoxPoliceRank.Text = functionary.Rank;
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Ocurrio un error al obtener el empleado");
            }

        }

        private void TxtBoxPoliceCI_GotFocus(object sender, RoutedEventArgs e)
        {
            search = new SearchFunctionary();
            search.getEmployee += new RoutedEventHandler(getEmployeeEventHandler);
            search.ShowDialog();
            TxtBoxPoliceCI.Focusable = false;
        }

        private void TxtBoxPoliceName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxPoliceCI_GotFocus(sender, e);
            TxtBoxPoliceName.Focusable = false;
        }

        private void TxtBoxPolicePName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxPoliceCI_GotFocus(sender, e);
            TxtBoxPolicePName.Focusable = false;
        }

        private void TxtBoxPoliceMName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxPoliceCI_GotFocus(sender, e);
            TxtBoxPoliceMName.Focusable = false;
        }

        private void TxtBoxPoliceRank_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxPoliceCI_GotFocus(sender, e);
            TxtBoxPoliceRank.Focusable = false;
        }
    }
}
